# -*- coding: utf-8 -*-
# --------------------------------------
# @Time    : 2025/6/19 22:24
# @File    : acount.py
# @Project : Practice_flask_0619
# @Author  : CHH
# @Desc    : Windows   文件描述
# @Copyright : © 2025 HORDOR . All rights reserved.
# @Version : 1.0.0
# --------------------------------------
from flask import Blueprint, request, render_template, redirect, url_for, session, flash
from utils import db

ac_bp = Blueprint('acount', __name__)


@ac_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    from utils import db
    user = request.form.get('username')
    pwd = request.form.get('pwd')
    user_dict = db.fetch_one("select * from user where username = %s and password = %s", (user, pwd))
    if user_dict is None:
        error = "Username or Password is incorrect"
        return render_template("login.html", error=error)
    session["user_info"] = user_dict
    return redirect("/index")


@ac_bp.route('/user/forgot', methods=["GET", "POST"])
def user_forgot():
    if request.method == 'POST':
        email = request.form['email']
        # 这里添加密码重置逻辑（发送邮件等）
        user_dict = db.fetch_one("select * from user where email=%s", (email,))
        if not user_dict:
            error = "该账户邮箱不存在"
            return render_template("./login/forgot.html", erro=error)

        print(f"密码重置请求来自: {email}")
        return redirect(url_for('acount.user_reset_sent', email=email))
    return render_template("./login/forgot.html")


@ac_bp.route('/user/register', methods=["GET", "POST"])
def user_register():
    if request.method == "GET":
        return render_template("./login/register.html")
    username = request.form.get("name")
    email = request.form.get("email")
    PhoneNumber = request.form.get("phonenumber")
    password = request.form.get("password")
    user_id = db.insert_one("insert into user (username,email,phonenumber,password) values (%s,%s,%s,%s)",
                            (username, email, PhoneNumber, password))
    flash('注册成功！', 'success')
    user_dict = db.fetch_one("select * from user where username = %s and password = %s", (username, password))
    session["user_info"] = user_dict

    return render_template("index.html")


@ac_bp.route('/user/reset_sent', methods=["GET", "POST"])
def user_reset_sent():
    email = ""
    if request.method == "GET":
        email = request.args.get("email")
        if email:
            return render_template("./login/reset.html", email=email)
        return "邮箱不存在"
    new_pwd = request.form.get("password")
    email = request.form.get("email")
    print(email, new_pwd)
    affected_rows = db.reset_one("UPDATE user SET password=%s WHERE email=%s", (new_pwd, email,))
    print(affected_rows)
    if affected_rows == 1:
        flash('密码已成功重置！请使用新密码登录。', 'success')
        # reset_info = '密码已成功重置！请使用新密码登录。'
        return redirect("/login")
    return "重置失败！"
